package JZ37_数字在升序数组中出现的次数;

public class Solution {
    public int GetNumberOfK(int [] array , int k){
        if (array.length == 0 || k < array[0] || k > array[array.length - 1]){
            return 0;
        }

        int left = 0;
        int right = array.length - 1;
        int count = 0;
        int found = -1;

        while (left <= right){
            int mid = (left + right) / 2;
            if (array[mid] > k){
                right = mid - 1;
            }else if (array[mid] < k){
                left = mid + 1;
            }else {
                count++;
                found = mid;
                break;
            }
        }
        if (found == -1){
            return 0;
        }

        left = found - 1;
        right = found + 1;
        if (left < 0 || right > array.length){
            return 1;
        }
        while (left >= 0 && array[left] == k){
            count++;
            left--;
        }
        while (right <= array.length - 1 && array[right] == k){
            count++;
            right++;
        }
        return count;
    }

    public static void main(String[] args) {
        int[] arr = {3};
        int k = 3;
        Solution solution = new Solution();

        int count = solution.GetNumberOfK(arr, k);
        System.out.println(count);
    }
}
